package org.zn.note.jdk.others;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName MyKey
 * @Author zn
 * @Date 2019/12/24 8:38
 **/
public class MyKey {

    public static void main(String[] args) throws Exception {
        String[] files = setFileName(args);
        byte[] b = fileToBytes(files[0]);
        xor(b);
        bytesToFile(b, files[1]);
    }

    private static void xor(byte[] bytes) {
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (bytes[i] ^ 0b11111111);
        }
    }

    private static byte[] fileToBytes(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        List<Byte> values = new ArrayList();
        int value;
        while (-1 != (value = in.read())) {
            values.add((byte) value);
        }
        byte[] bytes = byteListToArrays(values);
        return bytes;
    }

    private static void bytesToFile(byte[] bytes, String filePath) throws IOException {
        OutputStream out = new FileOutputStream(filePath);
        out.write(bytes);
        out.flush();
    }

    private static byte[] byteListToArrays(List<Byte> list) {
        byte[] b = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            b[i] = list.get(i);
        }
        return b;
    }

    private static String[] setFileName(String[] args) throws Exception {
        String[] files = new String[2];
        String s = args.length > 0 ? args[0] : new SimpleDateFormat("yyyyMM").format(new Date());
        String s2 = s + ".new";
        if (new File(s).exists() && new File(s2).exists())
            throw new Exception(s + " and " + s2 + " all exists!");
        if (!new File(s).exists() && !new File(s2).exists())
            throw new Exception(s + " and " + s2 + " all not exists!");
        if (new File(s).exists()) {
            files[0] = s;
            files[1] = s2;
        } else {
            files[0] = s2;
            files[1] = s;
        }
        return files;
    }
}